from django import forms
from django.forms import ModelForm
from django.utils import simplejson
from django.utils.safestring import mark_safe
from django.template import Context, Template
from django.template.loader import get_template

from pypsqueak.page.models import *

class PageBodyWidget(forms.Textarea):
	class Media:
		js = (
			"/files/lib/tinymce/js/tiny_mce.js",
			);

	def set_user(self, user):
		""" We need the owner of the page to render with the right css """
		self.user = user

	def render( self, name, value, attrs=None):
		if attrs == None:
			attrs = {'width':'10%'}

		output = super(PageBodyWidget, self).render(name, value, attrs)
		return mark_safe("""
<script type="text/javascript">

tinyMCE.init({
	mode : "textareas",
	theme : "advanced",
	plugins: "safari,fullscreen",

	content_css : "/files/css/Page/PageBodyWidget.css",
	width : "100%%",
	height : "360px",
	theme_advanced_source_editor_width : "100%%",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_resizing : true,
	theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,undo,redo,separator,forecolor,backcolor,,fontselect,fontsizeselect",
	theme_advanced_buttons2 : "bullist,numlist,separator,outdent,indent,separator,link,unlink,separator,image,separator,removeformat,separator,fullscreen",
	theme_advanced_buttons3 : "",
});

</script>
%(output)s
""" % {'username':self.user.username, 'output':output }
 )

class PageArtifactUploadWidget( forms.FileInput ):
	""" Provides Async File Upload """
	#self.user and self.page must be set

	class Media:
		css = {'all': ('/files/lib/jquery.uploadify-v1.6.2/uploadify.css',)}

		js = ( "/files/lib/jquery/js/jquery-1.3.2.min.js",
				"/files/lib/jquery.uploadify-v1.6.2/jquery.uploadify.js",
			);

	def render(self, name, value, attrs=None):
		output = super( ArtifactUploadWidget, self ).render(name, value, attrs)

		return mark_safe(
'''
<script type="text/javascript">
	$(document).ready(function() {
		$("#id_%(name)s").fileUpload ({
			"uploader"  : "%(uploader)s",
			"script"    : "%(artifact_insert_url)s",
			"scriptData": {'user':%(user_id)s,'page':%(page_id)s},
			"cancelImg" : "%(cancel_url)s",
			"auto"      : true,
			"buttonText": "Upload File",
			"folder"    : "None/"
		});
	});
</script>
<input type="file" name="%(name)s" id="id_%(name)s" />
''' %	{'name':name,
		'uploader':'/files/lib/jquery.uploadify-v1.6.2/uploader.swf',
		'artifact_insert_url':Artifact.get_insert_url(self.user),
		'cancel_url':'/files/lib/jquery.uploadify-v1.6.2/cancel.png',
		'user_id':self.user.pk,
		'page_id':self.page.pk
		}
)

class YuiPageBodyWidget(forms.Textarea):
	class Media:
		css= {
			'all': (
				"http://yui.yahooapis.com/2.7.0/build/fonts/fonts-min.css",
				"http://yui.yahooapis.com/2.7.0/build/editor/assets/skins/sam/simpleeditor.css",
				)
			}
		js = (
			"http://yui.yahooapis.com/2.7.0/build/yahoo-dom-event/yahoo-dom-event.js",
			"http://yui.yahooapis.com/2.7.0/build/element/element-min.js",
			"http://yui.yahooapis.com/2.7.0/build/container/container_core-min.js",
			"http://yui.yahooapis.com/2.7.0/build/editor/simpleeditor-min.js",
			);

	def render( self, name, value, attrs=None):
		output = super(YuiPageBodyWidget, self).render(name, value, attrs)
		return output + mark_safe(
'''
<script>
var myEditor = null;

(function() {
	//Setup some private variables
	var Dom = YAHOO.util.Dom,
	Event = YAHOO.util.Event;

	//The SimpleEditor config
	var myConfig = {
		height: '300px',
		dompath: false,
		focusAtStart: true,
		toolbar: {
			titlebar: '',
			buttons: [
				{ group: 'textstyle', label: 'Font Style',
					buttons: [
						{ type: 'push', label: 'Bold', value: 'bold' },
						{ type: 'push', label: 'Italic', value: 'italic' },
						{ type: 'push', label: 'Underline', value: 'underline' },
						{ type: 'separator' },
						{ type: 'select', label: 'Arial', value: 'fontname', disabled: true,
							menu: [
								{ text: 'Arial', checked: true },
								{ text: 'Arial Black' },
								{ text: 'Comic Sans MS' },
								{ text: 'Courier New' },
								{ text: 'Lucida Console' },
								{ text: 'Tahoma' },
								{ text: 'Times New Roman' },
								{ text: 'Trebuchet MS' },
								{ text: 'Verdana' }
							]
						},
						{ type: 'spin', label: '13', value: 'fontsize', range: [ 9, 75 ], disabled: true },
						{ type: 'separator' },
						{ type: 'color', label: 'Font Color', value: 'forecolor', disabled: true },
						{ type: 'color', label: 'Background Color', value: 'backcolor', disabled: true }
					]
				}
			]
		},
	};

	//Now let's load the SimpleEditor..
	myEditor = new YAHOO.widget.SimpleEditor('%(name)s', myConfig);
	myEditor.render();

})();

//Inside an event handler after the Editor is rendered
YAHOO.util.Event.on('save', 'click', function() {
	//Put the HTML back into the text area
	myEditor.saveHTML();
	alert('save');
	//The var html will now have the contents of the textarea
	//var html = myEditor.get('element').value;
});
</script>
''' %	{'name':"id_" +name }
 )


class ParentChoiceField(forms.ModelChoiceField):
	"""
	Field for choosing a parent page
	Provides nice tree-like structure as well as making it impossible to create parental cycles.
	"""

	def LoadPage( self, page ):
		""" Orders pages into proper order & with the correct depth """
		self.queryset = Page.objects.filter( user__id = page.user.id )

		# Populate all child pages from the cached qset to avoid requerying for each top-level branch.
		for p in self.queryset:
			if None == p.parent:
				p.populateRelations( self.queryset )

		def setorder_recurse( pages, depth, selected_page ):
			choices = []
			for p in pages:
				if p.pk != selected_page.pk:
					if selected_page.parent != None and p.pk == selected_page.parent.pk:
						choices.append( (p.id, depth + " " + p.title + " (current location)" ) )
					else:
						choices.append( (p.id, depth + " " + p.title) )
					choices.extend(setorder_recurse( p.getChildren(), depth + "--", selected_page ))
			return choices

		self.choices = setorder_recurse( page.user.getChildren(), "", page )
		self.choices.insert( 0, ('',"No parent page") )
		self.widget.choices = self.choices


class AutoCompleteTagWidget(forms.TextInput):
	"""
	Provides auto-complete for tags

	See http://jannisleidel.com/2008/11/autocomplete-widget-for-django-tagging-form-fields/ for documentation on this.
	"""
	class Media:
		css= {
			'all': (
				"http://yui.yahooapis.com/2.7.0/build/fonts/fonts-min.css",
				"http://yui.yahooapis.com/2.7.0/build/autocomplete/assets/skins/sam/autocomplete.css",
				)
			}
		js = (
			"http://yui.yahooapis.com/2.7.0/build/yahoo-dom-event/yahoo-dom-event.js",
			"http://yui.yahooapis.com/2.7.0/build/json/json-min.js",
			"http://yui.yahooapis.com/2.7.0/build/animation/animation-min.js",
			"http://yui.yahooapis.com/2.7.0/build/datasource/datasource-min.js",
			"http://yui.yahooapis.com/2.7.0/build/autocomplete/autocomplete-min.js",
			);

	def render(self, name, value, attrs=None):
		output = super( AutoCompleteTagWidget, self ).render(name, value, attrs)
		page_tags = value
		#tag_list = simplejson.dumps([tag.name for tag in Page.tags.get_query_set()], ensure_ascii=True)
		tag_list = ""
		return  mark_safe(u'''
<div id="myAutoComplete">
	<input id="id_tags_string" class="yui-ac-input" type="text" value="%s" name="tags_string" autocomplete="on"/>
	<div id="myContainer"></div>
</div>
<script type="text/javascript">

	// Use a LocalDataSource
	var oDS = new YAHOO.util.LocalDataSource( %s );
	// Optional to define fields for single-dimensional array
	//oDS.responseSchema = {fields : ["tags"]};

	// Instantiate the AutoComplete
	var oAC = new YAHOO.widget.AutoComplete("id_tags_string", "myContainer", oDS);
	oAC.prehighlightClassName = "yui-ac-prehighlight";
	oAC.useShadow = true;

</script>''' % (page_tags, tag_list))


def PageTreeNavigationWidget( user, selected_page=None ):
	""" Return the html for a navigation page tree, using the user provided.  """

	# Recurse
	children = "".join([PageTreeNavigationWidget(p, selected_page) for p in user.getChildren()])
	if children != "":
		children = "<ul>" + children + "</ul>"

	# If this isn't a user, then format it according to the template.
	if isinstance( user, Page ):
		c = Context( {"page": user, "selected": selected_page == user })
		t = get_template( 'page/pagetree_part.html')
		children = t.render( c ) + children

	return mark_safe(children)

